﻿using System;
using System.Drawing;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;

namespace YZAutoDWR.Handler;

public class ExcelHandler
{
    private static readonly string RootDirectory = AppDomain.CurrentDomain.BaseDirectory;
    private const string ExcelName = "工作日报.xlsx";
    private readonly string _filePath = Path.Combine(RootDirectory, ExcelName);

    public void GenerateExcelTemplate()
    {
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
        
        using var package = new ExcelPackage();

        var worksheet = package.Workbook.Worksheets.Add("每日任务表");
        SetHeaders(worksheet);
        SetStyles(worksheet);
        SetColumnWidths(worksheet);

        package.SaveAs(new FileInfo(_filePath));
    }

    private static void SetHeaders(ExcelWorksheet worksheet)
    {
        // 表头标题
        var headers = new[]
        {
            "类型", "日期", "项目", "工作类型", "计划任务",
            "预计时间", "计划完成时间", "实际任务", "实际工时",
            "状态", "备注"
        };

        // 填充表头
        for (var col = 1; col <= headers.Length; col++)
        {
            worksheet.Cells[1, col].Value = headers[col - 1];
        }
    }

    private static void SetStyles(ExcelWorksheet worksheet)
    {
        // 表头范围（A1:K1）
        var headerRange = worksheet.Cells["A1:K1"];
        
        headerRange.Style.Font.Name = "宋体";
        headerRange.Style.Font.Size = 10;
        headerRange.Style.Font.Bold = true;
        
        headerRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; // 居中
        headerRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
        headerRange.Style.WrapText = true; // 自动换行
        
        headerRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
        headerRange.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(204, 255, 204)); // 单元格背景色
    }

    private static void SetColumnWidths(ExcelWorksheet worksheet)
    {
        // 配置列宽
        const double defaultWidth = 128 / 7.29;
        const double columnHWidth = 512 / 7.29; // "实际任务"列的宽度
        
        for (var col = 1; col <= 11; col++)
        {
            worksheet.Column(col).Width = col == 8 ? columnHWidth : defaultWidth;
        }
    }
}